import 'package:flutter/material.dart';
import '../../services/api_service.dart';
import '../../utils/logger.dart';
import 'package:base_flutter/src/network/network_exception.dart';
import 'payment_page.dart';

/// 订单确认页面
class OrderConfirmPage extends StatefulWidget {
  final int serviceProductId;
  final Map<String, dynamic> serviceDetail;

  const OrderConfirmPage({
    super.key,
    required this.serviceProductId,
    required this.serviceDetail,
  });

  @override
  State<OrderConfirmPage> createState() => _OrderConfirmPageState();
}

class _OrderConfirmPageState extends State<OrderConfirmPage> {
  int _quantity = 1;
  bool _isCreatingOrder = false;

  @override
  Widget build(BuildContext context) {
    final priceInfo = widget.serviceDetail['priceInfo'] as Map<String, dynamic>?;
    final title = widget.serviceDetail['title'] as String? ?? '商品';
    final price = priceInfo?['price'] as double? ?? 0.0;
    final totalAmount = price * _quantity;

    return Scaffold(
      appBar: AppBar(
        title: const Text('确认订单'),
        backgroundColor: Colors.white,
        foregroundColor: Colors.black,
        elevation: 0,
      ),
      body: Column(
        children: [
          Expanded(
            child: SingleChildScrollView(
              child: Column(
                children: [
                  // 商品信息
                  _buildProductInfo(title, price),
                  const Divider(height: 1),
                  
                  // 数量选择
                  _buildQuantitySelector(),
                  const Divider(height: 1),
                  
                  // 订单金额
                  _buildOrderAmount(totalAmount),
                ],
              ),
            ),
          ),
          
          // 底部确认按钮
          _buildBottomBar(totalAmount),
        ],
      ),
    );
  }

  /// 商品信息
  Widget _buildProductInfo(String title, double price) {
    final mediaInfo = widget.serviceDetail['mediaInfo'] as Map<String, dynamic>?;
    final coverUrl = mediaInfo?['coverUrl'] as String?;

    return Container(
      padding: const EdgeInsets.all(16),
      color: Colors.white,
      child: Row(
        children: [
          // 商品封面
          Container(
            width: 80,
            height: 80,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(8),
              color: Colors.grey[200],
            ),
            child: coverUrl != null
                ? ClipRRect(
                    borderRadius: BorderRadius.circular(8),
                    child: Image.network(
                      coverUrl,
                      fit: BoxFit.cover,
                      errorBuilder: (context, error, stackTrace) {
                        return const Icon(Icons.shopping_bag, size: 40);
                      },
                    ),
                  )
                : const Icon(Icons.shopping_bag, size: 40),
          ),
          const SizedBox(width: 12),
          
          // 商品信息
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  title,
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w500,
                  ),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
                const SizedBox(height: 8),
                Text(
                  '¥${price.toStringAsFixed(2)}',
                  style: const TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                    color: Colors.red,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 数量选择
  Widget _buildQuantitySelector() {
    return Container(
      padding: const EdgeInsets.all(16),
      color: Colors.white,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          const Text(
            '购买数量',
            style: TextStyle(fontSize: 16),
          ),
          Row(
            children: [
              IconButton(
                onPressed: _quantity > 1 ? () => setState(() => _quantity--) : null,
                icon: const Icon(Icons.remove_circle_outline),
                color: _quantity > 1 ? Colors.blue : Colors.grey,
              ),
              Text(
                '$_quantity',
                style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
              ),
              IconButton(
                onPressed: () => setState(() => _quantity++),
                icon: const Icon(Icons.add_circle_outline),
                color: Colors.blue,
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// 订单金额
  Widget _buildOrderAmount(double totalAmount) {
    return Container(
      padding: const EdgeInsets.all(16),
      color: Colors.white,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          const Text(
            '订单金额',
            style: TextStyle(fontSize: 16),
          ),
          Text(
            '¥${totalAmount.toStringAsFixed(2)}',
            style: const TextStyle(
              fontSize: 20,
              fontWeight: FontWeight.bold,
              color: Colors.red,
            ),
          ),
        ],
      ),
    );
  }

  /// 底部操作栏
  Widget _buildBottomBar(double totalAmount) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.2),
            spreadRadius: 1,
            blurRadius: 3,
            offset: const Offset(0, -1),
          ),
        ],
      ),
      child: Row(
        children: [
          Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text('合计', style: TextStyle(fontSize: 14, color: Colors.grey)),
              Text(
                '¥${totalAmount.toStringAsFixed(2)}',
                style: const TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                  color: Colors.red,
                ),
              ),
            ],
          ),
          const Spacer(),
          SizedBox(
            width: 150,
            child: ElevatedButton(
              onPressed: _isCreatingOrder ? null : _confirmOrder,
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.blue,
                padding: const EdgeInsets.symmetric(vertical: 14),
                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
              ),
              child: _isCreatingOrder
                  ? const SizedBox(
                      width: 20,
                      height: 20,
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                        valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                      ),
                    )
                  : const Text(
                      '确认下单',
                      style: TextStyle(
                        fontSize: 16,
                        color: Colors.white,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
            ),
          ),
        ],
      ),
    );
  }

  /// 确认下单
  Future<void> _confirmOrder() async {
    setState(() => _isCreatingOrder = true);

    try {
      // 创建订单
      final orderData = await ApiService().createOrder(
        widget.serviceProductId,
        quantity: _quantity,
      );

      Logger.d('ORDER_CONFIRM', '订单创建成功: $orderData');

      if (!mounted) return;

      // 跳转到支付页面
      final result = await Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => PaymentPage(
            orderId: orderData['orderId'],
            orderNo: orderData['orderNo'],
            amount: orderData['amount'],
          ),
        ),
      );

      if (!mounted) return;

      // 返回支付结果
      if (result != null) {
        Navigator.pop(context, result);
      } else {
        Navigator.pop(context);
      }
    } catch (e) {
      Logger.e('ORDER_CONFIRM', '创建订单失败: $e');
      
      if (!mounted) return;
      
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('创建订单失败: ${e is NetworkException ? e.message : e.toString()}'),
          backgroundColor: Colors.red,
        ),
      );
    } finally {
      if (mounted) {
        setState(() => _isCreatingOrder = false);
      }
    }
  }
}
